package com.ABdolphin.captcha.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import com.ABdolphin.captcha.model.CaptchaProperties;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.Date;

@RestController
@RequestMapping("/captcha")
public class CaptchaController {

    private static Logger logger= LoggerFactory.getLogger(CaptchaController.class);
    @Autowired
    private CaptchaProperties captchaProperties;

    @GetMapping("/getCaptcha")
    public void captcha(HttpSession session,HttpServletResponse response){
        //生成验证码
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha
                (captchaProperties.getWidth(), captchaProperties.getHeight());
        //打印验证码
        String code=lineCaptcha.getCode();
        System.out.println("System随机生成验证码:"+code);
        logger.info("logger随机生成验证码:"+code);
        //存储 Session
        session.setAttribute(captchaProperties.getSession().getKey(),code);
        session.setAttribute(captchaProperties.getSession().getDate(),new Date());
        try {
            lineCaptcha.write((response.getOutputStream()));
            response.setContentType("image/jpeg");
            response.setCharacterEncoding("UTF-8");
            response.setHeader("Pragma","No-cache");
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @RequestMapping("/check")
    public boolean check(String captcha,HttpSession session){
        System.out.println("用户输入的验证码:"+captcha);
        if (!StringUtils.hasLength(captcha)){
            return false;
        }
        String code=(String) session.getAttribute(captchaProperties.getSession().getKey());
        Date date = (Date) session.getAttribute(captchaProperties.getSession().getDate());
        if (date==null||(System.currentTimeMillis()-date.getTime())>captchaProperties.getVALID_TIME_OUT()){
            return false;
        }

        return captcha.equalsIgnoreCase(code);


    }
}
